<template>
  <div class="msg-send">
    <MsgSendNav @send="sendMsg" />
    <div class="content-wrapper">
      <van-cell-group inset>
        <!-- 输入任意文本 -->
        <van-field v-model="msgInfo.messageSubject" label="主题" placeholder="请输入主题" :label-width="48" />
        <van-cell title="接收人" title-class="custom-title">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <div class="tag-list">
            <van-tag
              v-for="item of recipientList"
              :key="item.id"
              :show="true"
              color="#f5f5f5"
              text-color="#333333"
              closeable
              size="medium"
              @close="removeRecipientById(item.id)"
            >
              {{ item.username }}
            </van-tag>
          </div>
          <template #right-icon>
            <img class="right-icon-add" src="@/assets/msg/icon-add.svg" @click="showTopPop" />
          </template>
        </van-cell>
        <!-- <van-cell>
          <template #title>
            <van-uploader
              :max-size="200 * 1024 * 1024"
              :max-count="1"
              :after-read="afterRead"
            >
              <a class="custom-link">{{ msgInfo.files ? msgInfo.fileName : '添加附件(最大200M)' }}</a>
            </van-uploader>
          </template>
          <template #right-icon>
            <van-icon v-if="msgInfo.files" name="cross" @click="clearFileInfo" />
          </template>
        </van-cell> -->
        <van-field
          class="custom-textarea"
          v-model="msgInfo.content"
          type="textarea"
          placeholder="请输入内容"
        />
      </van-cell-group>
    </div>
    <!-- 选择收件人 -->
    <van-popup v-model:show="showTop" position="top">
      <div style="width: 100%; height: 64px;"></div>
      <van-search
        autofocus
        v-model="keyword"
        show-action
        placeholder="搜索用户"
        @search="onSearch"
        @cancel="onCancel"
      />
      <van-list style="height: 224px; overflow-y: auto;">
        <van-cell
          v-for="item in userList"
          :key="item.id"
          :title="item.username"
          @click="addRecipient(item)"
        />
      </van-list>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { showLoadingToast, closeToast, showToast } from 'vant'
import { useRouter } from 'vue-router'
import MsgSendNav from './components/MsgSendNav.vue'
import MsgSendServe from '@/api/msgSend'

interface IMsgInfo {
  messageSubject: string,
  recipient: string,
  files: string,
  fileName: string,
  content: string
}

const msgInfo = ref<IMsgInfo>({
  messageSubject: '',
  recipient: '',
  files: '',
  fileName: '',
  content: ''
})

interface IUserItem {
  id: string
  username: string
}

const recipientList = ref<IUserItem[]>([])

const router = useRouter()

// 发送消息
const sendMsg = () => {
  if (validate()) {
    msgInfo.value.recipient = recipientList.value.map(item => item.id).join(',')
    MsgSendServe.sendMessage(msgInfo.value).then(res => {
      showToast({  position: 'bottom', message: '消息发送成功' })
      router.back()
    }).catch(error => {
      showToast('消息发送失败')
      console.error('消息发送失败：', error)
    })
  }
}

// 校验必填项
const validate = () => {
  if (!msgInfo.value.messageSubject) {
    showToast('请输入主题')
    return false
  }
  if (recipientList.value.length === 0) {
    showToast('请添加接收人')
    return false
  }
  if (!msgInfo.value.content) {
    showToast('请输入内容')
    return false
  }
  return true
}

// 清除附件信息
const clearFileInfo = () => {
  msgInfo.value.files = ''
  msgInfo.value.fileName = ''
}

// 附件上传
const afterRead = (file: any) => {
  const formData = new FormData()
  formData.append('file', file.file)
  showLoadingToast({
    message: '正在上传...',
    duration: 0,
    forbidClick: true
  });
  MsgSendServe.fileUpload(formData).then(res => {
    const data = res.data || {}
    msgInfo.value.files = data.fileUrl
    msgInfo.value.fileName = data.name
  }).catch(error => {
    showToast('文件上传失败，请稍后再试')
    console.error(error)
  }).finally(() => {
    closeToast()
  })
}

// 显示搜索弹框
const showTop = ref<boolean>(false)
const showTopPop = () => {
  keyword.value = ''
  userList.value = []
  showTop.value = true
  onSearch()
}

// 取消添加
const onCancel = () => {
  showTop.value = false
}

// 移除收件人
const removeRecipientById = (id: string) => {
  recipientList.value = recipientList.value.filter(item => item.id !== id)
}

// 添加收件人
const addRecipient = (userItem: IUserItem) => {
  // 只有没添加过才添加
  if (!recipientList.value.some(item => item.id === userItem.id)) {
    recipientList.value.push(userItem)
  }
  showTop.value = false
}

// 搜索收件人
const keyword = ref<string>('')
const userList = ref<IUserItem[]>([])
const onSearch = () => {
  MsgSendServe.queryUser({ keyWord: keyword.value }).then(res => {
    userList.value = res.data || []
  }).catch(error => {
    showToast('搜索用户失败，请稍后再试')
    console.error('搜索用户失败：', error)
  })
}
</script>

<style lang="less" scoped>
.msg-send {
  height: 100vh;
  background-color: #fff;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;
  .content-wrapper {
    flex-grow: 1;
    overflow-y: scroll;
    z-index: 1;
    margin-top: -44px;
    border-radius: 19.23px 19.23px 0px 0px;
    background-color: #f5f5f5;
    .van-cell-group {
      height: calc(100% - 32px);
      margin: 16px;
      background: white;
      border-radius: 7.69px;
      :deep(.van-cell__title) {
        color: #a2a2a2;
      }
      :deep(.custom-title) {
        width: 48px;
        flex: none;
        padding-right: 12px;
      }
      .right-icon-add {
        width: 19.23px;
        height: 19.23px;
        margin-top: 2px;
      }
      .tag-list {
        width: 100%;
        text-align: left;
        display: flex;
        flex-flow: wrap;
        .van-tag {
          margin: 4px 12px 4px 0;
        }
      }
      .custom-link {
        color: #4389f3;
        text-decoration: underline;
      }
      .custom-textarea {
        :deep(textarea) {
          height: calc(100vh - 256px) !important;
        }
      }
    }
  }
}
</style>
